/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.httprequest;

import cn.ac.iie.di.global.GlobalParas;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import java.net.URLEncoder;

/**
 *
 * @author shipengfeng
 */
public class MyHttpRequest implements Runnable {

        Logger logger = Logger.getLogger(MyHttpRequest.class.getName());

        @Override
        public void run() {
                HttpURLConnection httpConn = null;
                try {
                        String urlPath = GlobalParas.httpPostAddr[0];

                        URL url = new URL(urlPath);
                        httpConn = (HttpURLConnection) url.openConnection();
                        //设置参数
                        httpConn.setDoOutput(true);   //需要输出
                        httpConn.setDoInput(true);   //需要输入
                        httpConn.setUseCaches(false);  //不允许缓存
                        httpConn.setRequestMethod("POST");   //设置POST方式连接
                        //设置请求属性
                        httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                        httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
                        httpConn.setRequestProperty("Charset", "UTF-8");
                        //连接,也可以不用明文connect，使用下面的httpConn.getOutputStream()会自动connect
                        httpConn.connect();

                        while (true) {
                                JSONObject jo = null;
                                try {
                                        jo = GlobalParas.send2RabbitmqPool.poll(20, TimeUnit.MILLISECONDS);
                                        if (jo != null) {
                                                long st = System.currentTimeMillis();
                                                while (true) {
                                                        if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                                                                String msg = jo.toJSONString();
                                                                String param = "name=" + URLEncoder.encode(msg, "UTF-8");
                                                                //建立输入流，向指向的URL传入参数
                                                                DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
                                                                dos.writeBytes(param);
                                                                dos.flush();
                                                                dos.close();
                                                                //获得响应状态
                                                                int resultCode = httpConn.getResponseCode();
                                                                if (HttpURLConnection.HTTP_OK == resultCode) {
                                                                        StringBuilder sb = new StringBuilder();
                                                                        String readLine = new String();
                                                                        BufferedReader responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
                                                                        while ((readLine = responseReader.readLine()) != null) {
                                                                                sb.append(readLine).append("\n");
                                                                        }
                                                                        responseReader.close();
                                                                        logger.info(sb.toString());
                                                                }
                                                                logger.info("send time is: " + (System.currentTimeMillis() - st));
                                                                break;
                                                        } else {
                                                                while (true) {
                                                                        try {
                                                                                httpConn.connect();
                                                                                break;
                                                                        } catch (Exception e) {
                                                                                logger.error("Reconnect failed, retry!");
                                                                                Thread.sleep(500);
                                                                        }
                                                                }

                                                        }
                                                }
                                        }
                                } catch (Exception e) {
                                        logger.error("Connection err or other err !");
                                        Thread.sleep(500);
                                }
                        }
                } catch (Exception ex) {
                        while (true) {
                                try {
                                        httpConn.connect();
                                        break;
                                } catch (Exception exs) {
                                        logger.info("Start connection failed! retry!");
                                        try {
                                                Thread.sleep(500);
                                        } catch (Exception e) {
                                        }

                                }
                        }
                }

        }
}
